<template>
  <div class="index">
    <!-- 顶部 -->
    <div class="top"><Admin></Admin></div>
    <!-- bottom -->
    <div class="bottom">
      <div class="left"><SideNav></SideNav></div>
      <div class="right">
        <div class="content">
          <el-scrollbar style="height: 100%;">
            <!-- 当前位置 -->
            <div class="current_position">
              <p class="breadcrumb">当前位置 :</p>
              <el-breadcrumb separator="/">
                <el-breadcrumb-item class="up">生活服务</el-breadcrumb-item>
                <el-breadcrumb-item class="up"><a @click="goTo('/Template')">模板商品</a></el-breadcrumb-item>
                <el-breadcrumb-item>新增模板</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <!-- 用户信息 -->
            <div class="userinformation">
              <div class="title">基本信息</div>
              <div class="message">
                <el-form ref="form" :model="form" label-width="80px">
                  <el-form-item label="一级分类:">
                    <el-select v-model="form.cname1" placeholder="请选择" @change="changeClassify1()">
                      <el-option
                        v-for="item in form.classify1"
                        :key="item.index"
                        :label="item.cname"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="二级分类:">
                    <el-select v-model="form.cname2" placeholder="请选择" @change="getClassify2()">
                      <el-option
                        v-for="item in form.classify2"
                        :key="item.index"
                        :label="item.cname"
                        :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="项目名称:">
                    <el-input v-model="form.title" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="产品主图:">

                    <div class="upload">
                      <el-upload class="uploadBox"
                        list-type="picture-card"
                        :file-list="fileListMainPic"
                        action
                        multiple
                        :limit="3"
                        :http-request="handleUploadMainPic"
                        :on-preview="handlePictureCardPreviewMainPic"
                        :on-remove="handleRemoveMainPic"
                        :class="{hide:hideUploadMainPic}">
                        <i class="el-icon-plus"><!-- <u>产品主图</u> --></i>
                      </el-upload>
                    </div>

                  </el-form-item>
                  <el-form-item label="路费:">
                    <el-input v-model="form.cost" clearable></el-input>
                    <i class="unit">元</i>
                  </el-form-item>
                  <el-form-item label="起步价:">
                    <el-input v-model="form.initiatePrice" clearable></el-input>
                    <i class="unit">元起</i>
                  </el-form-item>
                  <el-form-item label="标签:">
                    <el-checkbox-group v-model="form.label">
                      <el-checkbox v-for="(tag,index) in taglist" :label="tag.id" :key="index">{{tag.name}}</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item label="服务介绍:">
                    <!-- 图片上传组件辅助-->
                    <el-upload class="avatar-uploader"
                      action
                      multiple
                      :limit="30"
                      :headers="header"
                      :show-file-list="false"
                      :before-upload="beforeUpload">
                    </el-upload>
                    <!--富文本编辑器组件-->
                    <el-row v-loading="quillUpdateImg">
                      <quill-editor
                        v-model="form.introduce"
                        ref="myQuillEditor"
                        :options="editorOption"
                        @change="onEditorChange($event)"
                        @ready="onEditorReady($event)">
                      </quill-editor>
                    </el-row>
                  </el-form-item>
                  <el-form-item label="预约须知:">
                    <!-- 图片上传组件辅助-->
                    <el-upload class="avatar-uploader avatar-uploader1"
                      action
                      multiple
                      :limit="30"
                      :headers="header"
                      :show-file-list="false"
                      :before-upload="beforeUpload1">
                    </el-upload>
                    <!--富文本编辑器组件-->
                    <el-row v-loading="quillUpdateImg1">
                      <quill-editor
                        v-model="form.notice"
                        ref="myQuillEditor1"
                        :options="editorOption1"
                        @change="onEditorChange1($event)"
                        @ready="onEditorReady1($event)">
                      </quill-editor>
                    </el-row>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="onSubmit" class="savebtn">保存</el-button>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Admin from '@/components/Admin.vue'
  import SideNav from '@/components/SideNav.vue'
  //quill编辑器的字体
  var fonts = ['SimSun', 'SimHei','Microsoft-YaHei','KaiTi','FangSong','Arial','Times-New-Roman','sans-serif'];
  // 工具栏配置
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
    ['blockquote', 'code-block'],
    [{'header': 1}, {'header': 2}],               // custom button values
    [{'list': 'ordered'}, {'list': 'bullet'}],
    [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
    [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
    [{'direction': 'rtl'}],                         // text direction
   // [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
    //[{'header': [1, 2, 3, 4, 5, 6, false]}],
    [{'color': []}, {'background': []}],          // dropdown with defaults from theme
    //[{'font': fonts}],
    [{'align': []}],
    ['link', 'image', 'video'],
    ['clean']                                         // remove formatting button
  ]
  export default {
    name: 'TemplateDeatil',
    components:{
      Admin,
      SideNav
    },
    data () {
      return {
        form:{
          classify1:[],//一级类目
          cname1:'',
          classify2:[],//二级类目
          cname2:'',//
          title:'',//项目名称
          mainPic:'',//主图
          topImgs:'',//副图
          cost:'',//路费
          initiatePrice:'',//起步价
          label:[],//标签
          introduce:'',//服务介绍
          notice:'',//预约须知
        },
        fileListMainPic: [],//主图图片列表
        hideUploadMainPic: false,//隐藏主图上传图标的变量
        limitCountMainPic:1,//主图受限长度
        dialogImageUrlMainPic: '',//主图预览图片url
        dialogVisibleMainPic: false,//主图预览图片显示与否
        header: {token: localStorage.getItem('token')},  // 有的图片服务器要求请求头需要有token之类的参数，写在这里
        quillUpdateImg: false,
        quillUpdateImg1: false,
        editorOption: {  // 富文本编辑器配置
          placeholder: '',
          theme: 'snow',  // or 'bubble'
          modules: {
            /* imageDrop: true,      //图片拖拽
            imageResize:{          //放大缩小
              displaySize: true
            }, */
            toolbar: {
              container: toolbarOptions,  // 工具栏
              handlers: {
                'image': function (value) {
                  if (value) {
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            }
          }
        },
        editorOption1: {  // 富文本编辑器配置
          placeholder: '',
          theme: 'snow',  // or 'bubble'
          modules: {
            /* imageDrop: true,      //图片拖拽
            imageResize:{          //放大缩小
              displaySize: true
            }, */
            toolbar: {
              container: toolbarOptions,  // 工具栏
              handlers: {
                'image': function (value) {
                  if (value) {
                    document.querySelector('.avatar-uploader1 input').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            }
          }
        },
        taglist:[//标签
          {
            id:1,
            name:'时效保障'
          },
          {
            id:2,
            name:'明码标价'
          },
          {
            id:3,
            name:'超长保修'
          }
        ],
      }
    },
    mounted() {
      this.getClassify1()//获取一级分类
    },
    methods: {
      // 路由
      goTo(path) {
        this.$router.push(path);
      },
      //获取一级分类
      getClassify1(){
        this.$axios.post(this.baseURL1+'admin/goodsClassify/getAppGoodsClassifyList',{
          "parentId":0,
          "requestSource":"PC",
          "status":1,
        }).then((res)=>{
          console.log("所有一级类目",res)
          if(res.data.code==1){
            this.form.classify1 = res.data.data.records
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      },
      //更改一级类目的选项时
      changeClassify1(){
        console.log(this.form.cname1)
        this.form.cname2='';//先将类目二清空
        this.getClassify2()//获取二级分类
      },
      //获取二级分类
      getClassify2(){
        this.$axios.post(this.baseURL1+'admin/goodsClassify/getAppGoodsClassifyList',{
          "parentId":this.form.cname1,
          "requestSource":"PC",
          "status":1,
        }).then((res)=>{
          console.log("所有二级类目",res)
          if(res.data.code==1){
            this.form.classify2 = res.data.data.records
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })

      },
      // 获取阿里云签名
      getOssToken(){
        var _self = this;
        return new Promise((resolve,reject)=>{
          this.$axios.post(this.baseURL1+'getJsOssToken',{
            "requestSource":"PC"
          }).then(function(res){
            _self.aliyunOssToken = res.data.data;
            console.log(_self.aliyunOssToken,"通行证")
            resolve()
          }).catch(function(error){
            console.log(error);
          })
        })
      },
      // 主图上传图片
      handleUploadMainPic(option){
        console.log(option,"上传的图片");
        this.getOssToken().then(res=>{
          var _self = this;
          var getSuffix = option.file.name;
          var filename = option.file.uid + getSuffix.substring(getSuffix.lastIndexOf("."),getSuffix.length);
          // console.log(filename,'filename');
          var formData = new FormData();//注意formData里append添加的键的大小写
          formData.append('key', _self.aliyunOssToken.dir + filename); //存储在oss的文件路径
          formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
          formData.append('policy', _self.aliyunOssToken.policy); //policy
          formData.append('Signature', _self.aliyunOssToken.signature); //签名
          formData.append("file", option.file);//文件
          formData.append('success_action_status', 200); //成功后返回的操作码
          var url = _self.aliyunOssToken.host; //url
          var fileUrl = _self.aliyunOssToken.host +'/'+ _self.aliyunOssToken.dir + filename; //fileUrl文件路径
          console.log('fileUrl',fileUrl);
          this.$axios.post(url, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          }).then((res) => {
            console.log(res);
            if(res.status==200){
              this.$message({
                message: '上传成功',
                type: 'success'
              });
              this.fileListMainPic.push({ url: fileUrl });
              this.hideUploadMainPic = this.fileListMainPic.length >= this.limitCountMainPic;//隐藏上传图标
            }else{
              this.$message.error('上传失败！请重新上传');
            }
          })
          .catch((err) => {
             console.log("err:",err);
             this.$message.error('上传失败！请重新上传');
          })
        })
      },
      // 主图移除图片
      handleRemoveMainPic(file,fileList) {
        for(var j=0; j<this.fileListMainPic.length;j++){
          if(file.uid == this.fileListMainPic[j].uid ){
             this.fileListMainPic.splice(j,1);
          }
        }
        // console.log(this.fileListMainPic,"this.imgs删除更新后");
        this.hideUploadMainPic = this.fileListMainPic.length >= this.limitCountMainPic;//显示上传图标
      },
      // 主图预览图片
      handlePictureCardPreviewMainPic(file) {
        this.dialogImageUrlMainPic = file.url;
        this.dialogVisibleMainPic = true;
      },
      onEditorReady(){},
      onEditorChange(){},
      onEditorReady1(){},
      onEditorChange1(){},
      // 服务介绍---上传图片
      beforeUpload(option){
        this.getOssToken().then(res=>{
          this.quillUpdateImg = true
          var _self = this;
          var getSuffix = option.name;
          var filename = option.uid + getSuffix.substring(getSuffix.lastIndexOf("."),getSuffix.length);
          // console.log(filename,'filename');
          var formData = new FormData();//注意formData里append添加的键的大小写
          formData.append('key', _self.aliyunOssToken.dir + filename); //存储在oss的文件路径
          formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
          formData.append('policy', _self.aliyunOssToken.policy); //policy
          formData.append('Signature', _self.aliyunOssToken.signature); //签名
          formData.append("file", option);//文件
          formData.append('success_action_status', 200); //成功后返回的操作码
          var url = _self.aliyunOssToken.host; //url
          var fileUrl = _self.aliyunOssToken.host +'/'+ _self.aliyunOssToken.dir + filename; //fileUrl文件路径
          this.$axios.post(url, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          }).then((res) => {
            console.log(res,"res");// res为图片服务器返回的数据
            let quill = this.$refs.myQuillEditor.quill// 获取富文本组件实例
            if (res.status == 200) { // 如果上传成功
                let length = quill.getSelection().index;// 获取光标所在位置
                quill.insertEmbed(length, 'image', fileUrl) // 插入图片  res.info为服务器返回的图片地址
                quill.setSelection(length + 1) // 调整光标到最后
            } else {
                this.$message.error('图片插入失败')
            }
            this.quillUpdateImg = false // loading动画消失
          })
          .catch((err) => {
             console.log("err:",err);
             this.quillUpdateImg = false// loading动画消失
             this.$message.error('图片插入失败')
             // this.$message.error('上传失败！请重新上传');
          })
        })
      },
      // 预约须知---上传图片
      beforeUpload1(option){
        this.getOssToken().then(res=>{
          this.quillUpdateImg1 = true
          var _self = this;
          var getSuffix = option.name;
          var filename = option.uid + getSuffix.substring(getSuffix.lastIndexOf("."),getSuffix.length);
          // console.log(filename,'filename');
          var formData = new FormData();//注意formData里append添加的键的大小写
          formData.append('key', _self.aliyunOssToken.dir + filename); //存储在oss的文件路径
          formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid); //accessKeyId
          formData.append('policy', _self.aliyunOssToken.policy); //policy
          formData.append('Signature', _self.aliyunOssToken.signature); //签名
          formData.append("file", option);//文件
          formData.append('success_action_status', 200); //成功后返回的操作码
          var url = _self.aliyunOssToken.host; //url
          var fileUrl = _self.aliyunOssToken.host +'/'+ _self.aliyunOssToken.dir + filename; //fileUrl文件路径
          this.$axios.post(url, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          }).then((res) => {
            console.log(res,"res"); // res为图片服务器返回的数据
            let quill1 = this.$refs.myQuillEditor1.quill // 获取富文本组件实例
            if (res.status == 200) {// 如果上传成功
                let length = quill1.getSelection().index;// 获取光标所在位置
                quill1.insertEmbed(length, 'image', fileUrl)// 插入图片  res.info为服务器返回的图片地址
                quill1.setSelection(length + 1)// 调整光标到最后
            } else {
                this.$message.error('图片插入失败')
            }
            this.quillUpdateImg1 = false// loading动画消失
          })
          .catch((err) => {
             console.log("err:",err);
             this.quillUpdateImg1 = false// loading动画消失
             this.$message.error('图片插入失败')
             // this.$message.error('上传失败！请重新上传');
          })
        })
      },
      // 提交表单
      onSubmit() {
        console.log(this.form,"提交表单");
        console.log(this.fileListMainPic,"项目图片");
        var url =''//其他图片
        for(var i = 1; i < this.fileListMainPic.length; i++){
          url += this.fileListMainPic[i].url+ ","
        }
        // console.log("图片",url)
        var label = ''
        for(var i = 0; i < this.form.label.length; i++){
          label += this.form.label[i]+ ","
        }
        console.log("标签",label)
        // this.form.introduce = this.form.introduce.substring( this.form.introduce.indexOf("<p>") + 3, this.form.introduce.indexOf("</p>") - 0);//服务介绍
        // this.form.notice = this.form.notice.substring( this.form.notice.indexOf("<p>") + 3, this.form.notice.indexOf("</p>") - 0);//预约须知

        this.$axios.post(this.baseURL1+'admin/goodsMould/add',{
          "requestSource":"PC",
          "parentId":this.form.cname1,//一级类目
          "secondLevelId":this.form.cname2,//二级类目
          "mouldName":this.form.title,//项目名称
          "topPic":this.fileListMainPic[0].url,//主图
          "otherPic":url,//其他图
          "fare":this.form.cost,//路费
          "flagFallPrice":this.form.initiatePrice,//起步价
          "tag":label,//标签
          "serviceIntroduction":this.form.introduce,//服务介绍
          "appointmentNotice":this.form.notice,//预约须知
        }).then((res)=>{
          console.log("提交",res)
          if(res.data.code==0){
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            this.$router.go(-1);//返回上一层
          }else{
            this.$message({
              message: res.data.msg,
              type: 'error'
            });
          }
        }).catch((err)=>{
          console.log('request fail', err);
        })
      }
    },
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  @import '@/assets/css/index.scss'; //这个分号一定要写，要不会报错
  @import '@/assets/css/user.scss'; //这个分号一定要写，要不会报错
  .message{
    >>> .el-input{//输入框
      width: 200px;
    }
    >>> .el-input__inner{//输入框
      height: 35px;
      line-height: 35px;
    }
    >>> .el-upload--picture-card{//上传图片按钮
      width: 60px;
      height: 60px;
      line-height: 60px;
    }
    >>> .el-upload--picture-card i{//上传按钮
      line-height: 2;
    }
    >>> .el-upload-list__item{//上传图片
      width: 60px;
      height: 60px;
    }
    .unit{
      font-style: normal;
    }
    .savebtn{
      width: 70px;
      height: 35px;
      background-color: #f77116;
      color: #ffffff;
      text-align: center;
      margin-top: 20px;
    }
  }
  .quill-editor:not(.bubble) .ql-container,
  .quill-editor:not(.bubble) .ql-container .ql-editor,
  .quill-editor{/* 富文本编辑器类容高度 */
    height: 10rem;
    width: 53.125rem;
    padding-bottom: 1rem;
  }
  .ql-snow .ql-tooltip{
    top: 0!important;
    left: 0!important;
  }
  .ql-container.ql-snow {
    height: 150px;
  }
</style>
